package com.example.kotlinExample

import com.example.kotlinExample.Utils.addWaterMark
import com.itextpdf.text.BaseColor
import com.itextpdf.text.Element
import com.itextpdf.text.pdf.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import org.springframework.web.multipart.MultipartFile
import java.io.FileOutputStream
import java.util.*

/**
 *
 *
 * @author liliang
 */

// list 返回多个值
//fun foo(): List<Int> = listOf(1, 2, 3)
//fun main() {
//    foo().forEach { value -> println(value) }
//}

// Sequences
//fun foo(): Sequence<Int> = sequence {
//    for (i in 1..3) {
//        Thread.sleep(100)
//        yield(i)
//    }
//}
//
//fun main() {
//    foo().forEach { value -> println(value) }
//}


// 使用suspend
//suspend fun foo(): List<Int> {
//    delay(1000)
//    return listOf(1, 2, 3)
//}
//
//fun main() = runBlocking {
//    foo().forEach { value -> println(value) }
//}

//fun foo(): Flow<Int> = flow {
//    for (i in 1..3) {
//        delay(100)
//        emit(i)
//    }
//}

fun foo() = (1..8).asFlow()

fun main() = runBlocking {
    withTimeoutOrNull(250) {
        foo().collect { value -> println(value) }
    }
    foo().collect { value -> println(value) }
    println("Done")
}



object Utils {
    /**
     * 添加文字水印，并附加UUID
     * @param srcFile 待加水印文件
     * @param destFile 加水印后输出文件
     * @param text 文本内容
     * @throws Exception
     */
    fun addWaterMark(srcFile: String?, destFile: String, text: String?) {
        // 待加水印的文件
        val reader = PdfReader(srcFile)
        // 加完水印的文件
        val stamper = PdfStamper(reader, FileOutputStream(destFile))
        val total = reader.numberOfPages + 1
        var content: PdfContentByte

        // 设置透明度
        val gs = PdfGState()
        gs.setFillOpacity(0.3f)
        // 设置字体
        val base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED)
        // 循环对每页插入水印
        for (i in 1 until total) {
            // 水印的起始
            content = stamper.getOverContent(i)
            content.setGState(gs)
            content.setFontAndSize(base, 32f)
            // 开始
            content.beginText()
            // 设置颜色 默认为黑色
            content.setColorFill(BaseColor.BLACK)
            // 开始写入水印
            content.showTextAligned(Element.ALIGN_MIDDLE, text, 180f, 340f, 45f)
            content.showTextAligned(Element.ALIGN_MIDDLE, UUID.randomUUID().toString(), 140f, 240f, 45f)
            content.endText()
        }
        stamper.close()
    }
}